<!-- src/renderer/src/views/login/index.vue -->
<template>
  <div class="login-container">
    <!-- 背景图片 -->
    <img
      src="/images/login-bg.jpg"
      class="background-image"
    />
    
    <!-- 标题放在 login-content 外面 -->
    <div class="login-header">
      <h1>济南局案件管理系统</h1>
      <p>真实准确&nbsp;&nbsp;完整及时</p>
    </div>
    
    <div class="login-content">
      <div class="login-warp">
        <div v-if="isFirstRun" class="first-time-setup">
          <div class="welcome-message">
            <h2>欢迎使用</h2>
            <p>这是您第一次使用本系统，请设置管理员账户</p>
          </div>
        </div>
        
        <div class="login-con">
          <p>用户登录</p>
          
          <div class="demo-input-suffix">
            <!-- 用户名输入框 -->
            <div class="el-input el-input--prefix">
              <el-input
                v-model="form.username"
                placeholder="请输入用户名"
                :disabled="loading"
                size="large"
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </div>
            
            <!-- 密码输入框 -->
            <div class="el-input el-input--prefix">
              <el-input
                v-model="form.password"
                :type="showPassword ? 'text' : 'password'"
                placeholder="请输入密码"
                :disabled="loading"
                size="large"
                @keyup.enter="handleSubmit"
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
                <template #suffix>
                  <el-icon 
                    class="password-toggle"
                    @click="showPassword = !showPassword"
                  >
                    <View v-if="showPassword" />
                    <Hide v-else />
                  </el-icon>
                </template>
              </el-input>
            </div>
            
            <div v-if="errorMessage" class="error-message">
              {{ errorMessage }}
            </div>
            
            <div class="login-btn">
              <el-button 
                class="sign" 
                :class="{ disabled: loading || !form.username || !form.password }"
                @click="handleSubmit"
                :disabled="loading || !form.username || !form.password"
                size="large"
                type="primary"
              >
                <span v-if="loading">验证中...</span>
                <span v-else>{{ isFirstRun ? '初始化系统' : '登录' }}</span>
              </el-button>
              <el-button class="out" @click="handleExit" size="large">
                退出
              </el-button>
            </div>
          </div>
          
          <div v-if="!isFirstRun" class="login-tips">
            <p>提示：首次使用可随意输入用户名密码创建账户</p>
          </div>
          
          <div class="security-info">
            <p>🔒 数据本地加密存储 | ⏱️ 5分钟无操作自动锁定</p>
          </div>
        </div>
      </div>
      
      <div class="system-version">
        案件管理系统 | 技术支持: 信息技术所
      </div>
    </div>
  </div>
</template>

<!-- src/renderer/src/views/Login.vue -->
<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User,Lock } from '@element-plus/icons-vue'

    const router = useRouter()
    const form = ref({ username: '', password: '' })
    const loading = ref(false)
    const errorMessage = ref('')
    const showPassword = ref(false)
    const isFirstRun = ref(false)
    
    // 清除认证状态
    const clearAuthState = () => {
      localStorage.removeItem('isAuthenticated')
      localStorage.removeItem('sessionId')
    }

    // 检查是否是第一次运行
    const checkFirstRun = async () => {
      try {
        const result = await window.electronAPI.invoke('auth-initialize')
        isFirstRun.value = result.isFirstRun
        console.log('是否是第一次运行:', isFirstRun.value)
        
        if (result.error) {
          errorMessage.value = result.error
        }
      } catch (error) {
        console.error('初始化检查失败:', error)
        errorMessage.value = '系统初始化失败，请重启应用'
      }
    }

    // 处理表单提交
    const handleSubmit = async () => {
      if (!form.value.username || !form.value.password) {
        errorMessage.value = '请输入用户名和密码'
        return
      }

      if (form.value.password.length < 6) {
        errorMessage.value = '密码长度至少6位'
        return
      }

      loading.value = true
      errorMessage.value = ''

      try {
        let result
        if (isFirstRun.value) {
          console.log('执行首次设置')
          result = await window.electronAPI.invoke('auth-first-time-setup', {
            username: form.value.username.trim(),
            password: form.value.password
          })
        } else {
          console.log('执行正常登录')
          result = await window.electronAPI.invoke('auth-login', {
            username: form.value.username.trim(),
            password: form.value.password
          })
        }

          console.log('认证结果:', result)

          if (result.success) {
            // 清除旧的认证状态（如果有）
            clearAuthState()
            
            // 保存新的认证状态到本地存储
            localStorage.setItem('isAuthenticated', 'true')
            localStorage.setItem('sessionId', result.sessionId)
            
            if (isFirstRun.value) {
              ElMessage.success('系统初始化成功！')
            } else {
            ElMessage.success('登录成功！')
          }
          
          // 添加延迟确保状态保存完成
          setTimeout(() => {
            console.log('跳转到仪表板')
            router.push('/dashboard')
          }, 100)
          
        } else {
          errorMessage.value = result.error || '认证失败'
        }
      } catch (error) {
        console.error('登录失败:', error)
        errorMessage.value = '登录过程发生错误，请重试'
      } finally {
        loading.value = false
      }
    }

    // 退出系统
    const handleExit = () => {
      ElMessageBox.confirm('确定要退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.electronAPI.invoke('app-quit')
      }).catch(() => {
        // 用户取消退出
      })
    }

    onMounted(() => {
      checkFirstRun()
      
      // 清除可能存在的无效认证状态
      clearAuthState()
      
      // 检查是否已认证
      const isAuthenticated = localStorage.getItem('isAuthenticated')
      if (isAuthenticated) {
        console.log('已认证，跳转到仪表板')
        router.push('/dashboard')
      }
    })
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  height: 100%;
  overflow: hidden;
}

.login-container {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  overflow: hidden;
}

.background-image {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  -webkit-user-drag: none;
  user-select: none;
  z-index: 1;
}

/* 标题样式 */
.login-header {
  position: relative;
  z-index: 2;
  text-align: center;
  margin-bottom: 30px;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
  width: 100%;
  max-width: 1000px;
}

.login-header h1 {
  color: #c20d22;
  margin-bottom: 10px;
  font-weight: bold;
  line-height: 1.3;
  white-space: nowrap;
  overflow: visible;
  text-overflow: unset;
}

.login-header p {
  font-size: 16px;
  opacity: 0.9;
  white-space: nowrap;
  color: #3e3a39;
  font-family: HiraginoSansGB-W3, HiraginoSansGB;
  letter-spacing: .104167rem;
  font-weight: 800;
  font-size: 1.125rem;
}

/* 登录内容区域 */
.login-content {
  position: relative;
  z-index: 2;
  width: 100%;
  max-width: 500px;
  display: flex;
  flex-direction: column;
  align-items: center;
  max-height: 100%;
  overflow-y: auto;
}

.login-warp {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  width: 100%;
  padding: 30px;
  text-align: center;
}

.login-con {
  margin-top: 10px;
}

.login-con > p {
  font-size: 20px;
  color: #b71c1c;
  margin-bottom: 25px;
  font-weight: bold;
}

.demo-input-suffix {
  margin-bottom: 10px;
}

.el-input {
  position: relative;
  margin-bottom: 20px;
}

/* 自定义 Element UI 输入框样式 */
:deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 6px;
  box-shadow: 0 0 0 1px #ddd inset;
  transition: all 0.3s;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #b71c1c inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #b71c1c inset;
}

:deep(.el-input__inner) {
  font-size: 15px;
}

:deep(.el-input__prefix) {
  color: #999;
  margin-right: 8px;
}

:deep(.el-input__suffix) {
  color: #666;
  margin-left: 8px;
}

.password-toggle {
  cursor: pointer;
  transition: color 0.3s;
}

.password-toggle:hover {
  color: #b71c1c;
}

.login-btn {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  gap: 15px;
}

.sign, .out {
  flex: 1;
  height: 45px;
  border-radius: 6px;
  font-size: 16px;
  font-weight: bold;
  transition: all 0.3s;
}

:deep(.el-button) {
  width: 100%;
}

:deep(.el-button--primary) {
  background: #b71c1c;
  border-color: #b71c1c;
}

:deep(.el-button--primary:hover) {
  background: #9c1a1a;
  border-color: #9c1a1a;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(156, 26, 26, 0.3);
}

:deep(.el-button--primary.is-disabled) {
  background: #cccccc;
  border-color: #cccccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

:deep(.el-button:not(.el-button--primary)) {
  background: #f5f5f5;
  color: #666;
  border-color: #ddd;
}

:deep(.el-button:not(.el-button--primary):hover) {
  background: #e0e0e0;
  border-color: #ddd;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.first-time-setup {
  background: #e8f4fd;
  border: 1px solid #b8daff;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 20px;
}

.welcome-message h2 {
  color: #004085;
  margin: 0 0 10px 0;
  font-size: 18px;
}

.welcome-message p {
  color: #004085;
  margin: 0;
  font-size: 14px;
}

.error-message {
  background: #fee;
  color: #c33;
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 15px;
  font-size: 14px;
  border-left: 4px solid #c33;
}

.login-tips {
  margin-top: 20px;
  text-align: center;
  font-size: 13px;
  color: #666;
  padding: 10px;
  background: #f9f9f9;
  border-radius: 4px;
}

.security-info {
  margin-top: 20px;
  text-align: center;
  font-size: 12px;
  color: #999;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.system-version {
  margin-top: 20px;
  text-align: center;
  color: rgba(255, 255, 255, 0.9);
  font-size: 12px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-header h1 {
    font-size: 24px;
    white-space: normal;
    line-height: 1.4;
  }
  
  .login-header p {
    font-size: 14px;
  }
  
  .login-header {
    margin-bottom: 20px;
  }
}

@media (max-width: 480px) {
  .login-header h1 {
    font-size: 20px;
  }
  
  .login-header p {
    font-size: 13px;
  }
  
  .login-container {
    padding: 10px;
  }
  
  .login-warp {
    padding: 20px;
  }
}
</style>